<?php

use Illuminate\Database\Eloquent\RelationNotFoundException;

/**
 * 自动处理URL懒加载
 * @param $item
 * @return mixed
 * @throws \Psr\Container\ContainerExceptionInterface
 * @throws \Psr\Container\NotFoundExceptionInterface
 */
function get_include($item)
{
    $request = request();
    if ($request->has('include')) {
        $includes = explode(',', $request->get('include'));
        // 预加载一波
        try {
            $item->load($includes);
        } catch (RelationNotFoundException $e) {
        }
    }
    return $item;
}


/**
 * 获取模型状态码map
 *
 * @param $key
 * @param string $namespace
 * @return mixed
 */
function model_code_map($key, $namespace='Models')
{
    $array = explode('.', $key);
    $modelName = Str::studly($array[0]);
    $statusName = Str::camel($array[1]);

    $className = "App\\{$namespace}\\{$modelName}";
    $statusMapName = $statusName . 'Map';

    $map = [];
    if (property_exists($className, $statusMapName)) {
        $map = $className::$$statusMapName;
    }

    return $map;
}



/**
 * 解析model的状态码
 *
 * @param $key
 * @param $code
 * @param string $namespace
 * @return mixed|null
 */
function get_model_code($key, $code, $namespace='Models')
{
    $map = model_code_map($key);

    return isset($map[$code]) ? $map[$code] : null;
}




/**
 * post 操作
 * @param $url
 * @param $param
 * @param $headers
 * @return false|mixed
 */
function http_post($url, $param, $headers)
{

    $curl = curl_init();
    $headers =  array_merge($headers, [
        'access-control-allow-origin: *',
        'User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
        'Accept: application/json, text/plain, */*',
        'Connection: keep-alive',
        'Content-Type: multipart/form-data'
    ]);
    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => $param,
        CURLOPT_HTTPHEADER => $headers
    ));
    $response = curl_exec($curl);
    $status = curl_getinfo($curl);
    curl_close($curl);

    if($status["http_code"] == '200'){
        return json_decode($response, true);
    }else{
        return false;
    }
}

/**
 * post 操作
 * @param $url
 * @param $param
 * @param $headers
 * @return false|mixed
 */
function http_post_a($url, $param, $headers, $curlArray = [])
{

    $curl = curl_init();
    $headers =  array_merge($headers, [
        'access-control-allow-origin: *',
        'User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
        'Connection: keep-alive',
        'Content-Type: application/json'
    ]);
    $rArray = array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => $param,
        CURLOPT_HTTPHEADER => $headers
    );
    foreach ($curlArray as $item => $value) {
        $rArray[$item] = $value;
    }
    curl_setopt_array($curl, $rArray);
    $response = curl_exec($curl);
    $status = curl_getinfo($curl);
    curl_close($curl);


    if($status["http_code"] == '200'){
        if(count($curlArray) > 0) {
            \Log::info(json_decode($response, true));
        }
        return json_decode($response, true);
    }else{
        return false;
    }
}

/**
 * post 操作
 * @param $url
 * @param $param
 * @param $headers
 * @return false|mixed
 */
function http_post_x($url, $param, $headers)
{

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => http_build_query($param),
        CURLINFO_HEADER_OUT => 1,
        CURLOPT_HTTPHEADER => array_merge($headers, [
            'access-control-allow-origin: *',
            'User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
            'Accept: application/json, text/plain, */*',
            'Connection: keep-alive',
            'Content-Type: application/x-www-form-urlencoded;charset=UTF-8'
        ]),
    ));

    $response = curl_exec($curl);
    $status = curl_getinfo($curl);
    curl_close($curl);

    if($status["http_code"] == '200'){
        return json_decode($response, true);
    }else{
        return false;
    }
}


/**
 * @param $url
 * @param $param
 * @param $headers
 * @return false|mixed
 */
function http_get($url, $param, $headers)
{

    // 转义
    if (is_string($param)) {
        $strPOST = $param;
    } else {
        $aPOST = array();
        foreach($param as $key=>$val){
            $aPOST[] = $key."=".urlencode($val);
        }
        $strPOST =  join("&", $aPOST);
    }
    $url .= $strPOST ? ("?" . $strPOST) : '';

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
        CURLOPT_HTTPHEADER => $headers,
    ));

    $response = curl_exec($curl);
    $status = curl_getinfo($curl);
    curl_close($curl);
    if(intval($status["http_code"])==200){
        return json_decode($response, true);
    }else{
        return false;
    }

}



/**
 * 获取百度开放平台的票据
 * 参考链接：https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu
 * @param $grantType
 * @return mixed|void
 */
function get_ai_baidu_token($grantType = 'client_credentials')
{

    $url = 'https://aip.baidubce.com/oauth/2.0/token';
    $post_data['grant_type'] = $grantType;
    $post_data['client_id'] = env('AI_BAIDU_API_KEY');
    $post_data['client_secret'] = env('AI_BAIDU_SECRET_KEY');
    $o = "";
    foreach ($post_data as $k => $v) {
        $o .= "$k=" . urlencode($v) . "&";
    }
    $post_data = substr($o, 0, -1);

    $res = http_post($url, $post_data, []);
    if (isset($res['error'])) {
        exit('API Key或者Secret Key不正确');
    }
    return $res['access_token'];
}

/**
 * 获取毫秒数
 * @return float
 */
function get_microtime()
{
    $arr = explode(' ', microtime());
    return (float) sprintf('%.0f', (floatval($arr[0]) + floatval($arr[1])) * 1000);
}

/**
 * 获取验证码数据
 * @param $imageUrl
 * @return false|mixed
 */
function get_img_code($imageUrl)
{
    try {
        // 图片base64
        $base64 = 'data:image/png;base64,' . base64_encode(file_get_contents($imageUrl));
        //你申请的key密钥
        $API_KEY = env('345_API_KEY');
        //API接口地址
        $API_URL = 'https://www.345api.cn/api/code/ocr';
        $post_data = array(
            //接口参数，一行一个，可按照用户控制台->开发工具 的参数填写，或者直接复制开发工具下面的测试代码。
            'key' => $API_KEY,
            'data' => $base64
        );
        $result = http_post($API_URL, $post_data, []);
        if ($result['code'] != 200) {
            return ['status' => 'error', 'message' => $result['msg']];
        }
        return ['status' => 'success', 'code' => $result['data']['code_data']];
    } catch (\Exception $e) {
        return ['status' => 'error', 'message' => $e->getMessage()];
    }

}
